import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tender_flutter/constant/app_config.dart';
import 'package:tender_flutter/constant/app_constant.dart';
import 'package:tender_flutter/constant/resource_path.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/dialog/normal_text_dialog.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/track/item/track_list_cell.dart';
import 'package:tender_flutter/page/track/model/track_entity.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/toast.dart';
import 'package:tender_flutter/widgets/animation_dialog.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';
import 'package:tender_flutter/widgets/load_state_layout.dart';

import 'api/api_track.dart';

class TabTrackPage extends StatefulWidget {
  @override
  _TabTrackPageState createState() => _TabTrackPageState();
}

class _TabTrackPageState extends State<TabTrackPage>
    with AutomaticKeepAliveClientMixin {
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  Future<ApiResponse<TrackEntity>> _future;

  LoadState _loadState = LoadState.State_Loading;

  int page = AppConfig.page;

  int pageCount = AppConfig.pageCount;

  List<TrackList> _dataLists = [];

  ///下拉刷新
  void _onRefresh() {
    page = 1;
    setState(() {
      _future = _getData();
    });
  }

  /// 加载更多
  void _onLoading() {
    page += 1;
    setState(() {
      _future = _getData();
    });
  }

  /// 获取数据
  Future<ApiResponse<TrackEntity>> _getData() async {
    var response = await ApiTrack.getTrackList<TrackEntity>(
      page: page,
      pageCount: pageCount,
    );

    if (_refreshController.isLoading) {
      _refreshController.loadComplete();
    }
    if (_refreshController.isRefresh) {
      _refreshController.refreshCompleted();
    }
    return response;
  }

  /// 取消追踪
  Future<bool> _deleteData(
      int position, String companyName, String companyKey) async {
    var response = await ApiTrack.addTrack(
        companyName: companyName, companyKey: companyKey);
    if (response.status == Status.SUCCESS) {
      ToastUtils.show("取消成功");
    }
    return response.status == Status.SUCCESS ? true : false;
  }

  FutureBuilder<ApiResponse<TrackEntity>> _buildFutureBuilder() {
    return FutureBuilder(
        future: _future,
        // ignore: missing_return
        builder: (BuildContext context,
            AsyncSnapshot<ApiResponse<TrackEntity>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              TrackEntity entity = snapshot.data.result;
              if (snapshot.data.status == Status.SUCCESS) {
                List temps = entity.xList == null ? [] : entity.xList;
                page == AppConfig.page
                    ? _dataLists = temps
                    : _dataLists += temps;
                if (_dataLists.isEmpty) {
                  _loadState = LoadState.State_Empty;
                } else {
                  _loadState = LoadState.State_Success;
                }
              } else {
                _loadState = LoadState.State_Error;
              }
            } else if (snapshot.hasError) {
              _loadState = LoadState.State_Error;
            }

            /// 结束刷新，处理分页
            if (_dataLists.length % AppConfig.pageCount != 0) {
              _refreshController.loadNoData();
            } else {
              if (_refreshController.isLoading) {
                _refreshController.loadComplete();
              }
            }
            if (_refreshController.isRefresh) {
              _refreshController.refreshCompleted();
            }
          }

          return LoadStateLayout(
            state: _loadState,
            successWidget: _initList(),
            emptyWidget: _emptyView(),
          );
        });
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    _future = _getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _initAppBar(),
      body: _buildFutureBuilder(),
    );
  }

  /// 导航
  Widget _initAppBar() {
    return BaseAppBar(
      context,
      Text("企业追踪", style: FonStyle.navTextStyle()),
      backgroundColor: ThemeColors.colorWhite,
      actions: <Widget>[
        InkWell(
            onTap: () {
              LRouter.navigatorCtx(context)
                  .push(Routes.trackAddPage)
                  .then((value) => {
                        if (value ?? false)
                          {
                            // 需要刷新页面
                            if (_loadState != LoadState.State_Success)
                              {_onRefresh()}
                            else
                              {_refreshController.requestRefresh()}
                          }
                      });
            },
            child: IntrinsicHeight(
                child: Container(
                    alignment: Alignment.center,
                    padding: EdgeInsets.only(
                        left: ScreenAdapter.width(15),
                        right: ScreenAdapter.width(30)),
                    child: Text("+添加",
                        style: TextStyle(color: ThemeColors.colorType6))))),
      ],
      isShowLeading: false,
    );
    ;
  }

  /// 内容体
  Widget _initList() {
    return SmartRefresher(
        controller: _refreshController,
        enablePullUp: true,
        enablePullDown: true,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: ListView.separated(
          itemCount: _dataLists.length,
          itemBuilder: (BuildContext context, int index) {
            TrackList model = _dataLists[index];
            return TrackListCell(
                data: model,
                deleteCallback: () async {
                  var result = await showAnimationDialog(
                      context: context,
                      transitionType: TransitionType.rotation,
                      builder: (context) {
                        return NormalTextDialog(
                          content: "确定取消追踪？",
                        );
                      });
                  if (result == AppConstant.DIALOG_ACTION_CONFIRM) {
                    bool success = await _deleteData(
                        index, model.companyName, model.companyKey);
                    if (success) {
                      setState(() {
                        _dataLists.remove(model);
                      });
                    }
                  }
                },
                onTap: () {
                  LRouter.navigatorCtx(context).push(Routes.trackDynamicPage,
                      arguments: TrackDynamicPageArguments(
                          companyKey: model.companyKey,
                          companyName: model.companyName));
                });
          },
          separatorBuilder: (BuildContext context, int index) {
            return Divider(
              height: ScreenAdapter.height(10),
              color: ThemeColors.colorType11,
            );
          },
        ));
  }

  Widget _emptyView() {
    return Container(
        width: double.infinity,
        height: double.infinity,
        alignment: Alignment.center,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Image.asset(RPath.imgPath + 'img_empty.png',
                width: ScreenAdapter.width(200),
                height: ScreenAdapter.height(200)),
            SizedBox(height: ScreenAdapter.height(30)),
            Text(
              "您还未追踪任何企业!",
              style: TextStyle(
                  color: ThemeColors.colorType50,
                  fontSize: ScreenAdapter.sp(30)),
            ),
            Text(
              "\n请添加您要追踪的企业\n该企业有任何信息变动将第一时间推送给您",
              textAlign: TextAlign.center,
              style: TextStyle(
                  color: ThemeColors.colorType62,
                  fontSize: ScreenAdapter.sp(24)),
            ),
            GestureDetector(
              child: Container(
                  height: ScreenAdapter.height(90),
                  width: ScreenAdapter.width(600),
                  margin: EdgeInsets.only(top: ScreenAdapter.height(100)),
                  decoration: BoxDecoration(
                      color: ThemeColors.colorType6,
                      borderRadius:
                          BorderRadius.circular(ScreenAdapter.width(14))),
                  child: FlatButton(
                      onPressed: () {
                        LRouter.navigatorCtx(context)
                            .push(Routes.trackAddPage)
                            .then((value) => {
                                  if (value ?? false)
                                    {
                                      // 需要刷新页面
                                      if (_loadState != LoadState.State_Success)
                                        {_onRefresh()}
                                      else
                                        {_refreshController.requestRefresh()}
                                    }
                                });
                      },
                      child: Text("立即追踪",
                          style: TextStyle(
                              color: ThemeColors.colorWhite,
                              fontSize: ScreenAdapter.sp(32))))),
            )
          ],
        ));
  }
}
